﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Drawing.Design;
using System.Text.RegularExpressions;
using System.Security.Permissions;
using System.Globalization;
using System.Drawing;
using Beetle.Web.Composite;
using Beetle.Web.Extensions;

namespace Beetle.Web.UI.WebControls
{
    /// <summary>
    /// 为用户输入显示一个文本框且带自动验证功能的控件。 
    /// </summary>
    /// <!-- 作者:韦腾  时间:2010年02月09日 -->
    [Themeable(true), ParseChildren(true, "Text"), SupportsEventValidation, ControlBuilder(typeof(TextBoxControlBuilder)), ControlValueProperty("Text"), DataBindingHandler("System.Web.UI.Design.TextDataBindingHandler, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), DefaultProperty("Text"), ValidationProperty("Text"), DefaultEvent("TextChanged"), Designer("System.Web.UI.Design.WebControls.PreviewControlDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
    AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    public class ValidTextBox : System.Web.UI.WebControls.BaseValidator, IPostBackDataHandler, IEditableTextControl, ITextControl, IExtensibleObject<ValidTextBox>, IEditStatus
    {
        private static readonly object EventTextChanged = new object();
        private static readonly object EventServerValidate = new object();

        private const int DefaultMutliLineColumns = 20;
        private const int DefaultMutliLineRows = 2;

        /// <summary>
        /// 获取文本框控件的 HTML 标记。此属性是受保护的。
        /// </summary>
        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                bool isEditMode = this.GetEditMode();

                if (isEditMode)
                {
                    if (this.TextMode == TextBoxMode.MultiLine)
                    {
                        return HtmlTextWriterTag.Textarea;
                    }

                    return HtmlTextWriterTag.Input;
                }
                else
                {
                    return HtmlTextWriterTag.Span;
                }
            }
        }

        /// <summary>
        /// 获取或设置确定字段验证模式的正则表达式。
        /// </summary>
        [Category("Behavior")]
        [Description("获取或设置确定字段验证模式的正则表达式。")]
        [Themeable(true)]
        [DefaultValue("")]
        [Editor("System.Web.UI.Design.WebControls.RegexTypeEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
        public string ValidationExpression
        {
            get
            {
                object obj2 = this.ViewState["ValidationExpression"];
                if (obj2 != null)
                {
                    return (string)obj2;
                }

                return string.Empty;
            }
            set
            {
                try
                {
                    Regex.IsMatch(string.Empty, value);
                }
                catch (Exception exception)
                {
                    throw new HttpException("test", exception);
                }

                this.ViewState["ValidationExpression"] = value;
            }
        }

        /// <summary>
        /// 获取或设置一个值，用于指示能否更改 ValidTextBox 控件的内容。
        /// </summary>
        [DefaultValue(false), Themeable(false), Category("Behavior")]
        [Description("获取或设置一个值，用于指示能否更改 ValidTextBox 控件的内容。"), Bindable(true)]
        public virtual bool ReadOnly
        {
            get
            {
                object obj2 = this.ViewState["ReadOnly"];
                return ((obj2 != null) && ((bool)obj2));
            }
            set
            {
                this.ViewState["ReadOnly"] = value;
            }
        }

        /// <summary>
        /// 获取或设置一个值，该值表示 ValidTextBox 控件失去焦点时是否发生自动回发到服务器的操作。
        /// </summary>
        [Themeable(false), Category("Behavior")]
        [Description("获取或设置一个值，该值表示 ValidTextBox 控件失去焦点时是否发生自动回发到服务器的操作。"), DefaultValue(false)]
        public virtual bool AutoPostBack
        {
            get
            {
                object obj2 = this.ViewState["AutoPostBack"];
                return ((obj2 != null) && ((bool)obj2));
            }
            set
            {
                this.ViewState["AutoPostBack"] = value;
            }
        }

        /// <summary>
        /// 获取或设置一个值，该值指示当 ValidTextBox 控件设置为在回发发生时进行验证，是否执行验证。
        /// </summary>
        [Description("获取或设置一个值，该值指示当 ValidTextBox 控件设置为在回发发生时进行验证，是否执行验证。")]
        [DefaultValue(false), Themeable(true), Category("Behavior")]
        public virtual bool CausesValidation
        {
            get
            {
                object obj2 = this.ViewState["CausesValidation"];
                return ((obj2 != null) && ((bool)obj2));
            }
            set
            {
                this.ViewState["CausesValidation"] = value;
            }
        }

        /// <summary>
        /// 获取或设置 ValidTextBox 控件的行为模式（单行、多行或密码）。
        /// </summary>
        [Themeable(false), DefaultValue(0), Category("Behavior")]
        [Description("获取或设置 ValidTextBox 控件的行为模式（单行、多行或密码）。")]
        public virtual TextBoxMode TextMode
        {
            get
            {
                object obj2 = this.ViewState["Mode"];
                if (obj2 != null)
                {
                    return (TextBoxMode)obj2;
                }
                return TextBoxMode.SingleLine;
            }
            set
            {
                if ((value < TextBoxMode.SingleLine) || (value > TextBoxMode.Password))
                {
                    throw new ArgumentOutOfRangeException("value");
                }

                this.ViewState["Mode"] = value;
            }
        }

        /// <summary>
        /// 获取或设置文本框的显示宽度（以字符为单位）。
        /// </summary>
        [Category("Appearance"), DefaultValue(0)]
        [Description("获取或设置文本框的显示宽度（以字符为单位）。")]
        public virtual int Columns
        {
            get
            {
                object obj2 = this.ViewState["Columns"];
                if (obj2 != null)
                {
                    return (int)obj2;
                }

                return 0;
            }
            set
            {
                if (value < 0)
                {
                    throw new ArgumentOutOfRangeException("Columns", "");
                }

                this.ViewState["Columns"] = value;
            }
        }

        /// <summary>
        /// 获取或设置多行文本框中显示的行数。
        /// </summary>
        [Themeable(false), Category("Behavior"), DefaultValue(0)]
        [Description("获取或设置多行文本框中显示的行数。")]
        public virtual int Rows
        {
            get
            {
                object obj2 = this.ViewState["Rows"];
                if (obj2 != null)
                {
                    return (int)obj2;
                }
                return 0;
            }
            set
            {
                if (value < 0)
                {
                    throw new ArgumentOutOfRangeException("Rows", "");
                }

                this.ViewState["Rows"] = value;
            }
        }

        /// <summary>
        /// 获取或设置一个值，该值指示多行文本框内的文本内容是否换行。
        /// </summary>
        [Category("Layout"), DefaultValue(true)]
        [Description("获取或设置一个值，该值指示多行文本框内的文本内容是否换行。")]
        public virtual bool Wrap
        {
            get
            {
                object obj2 = this.ViewState["Wrap"];
                if (obj2 != null)
                {
                    return (bool)obj2;
                }
                return true;
            }
            set
            {
                this.ViewState["Wrap"] = value;
            }
        }

        /// <summary>
        /// 获取或设置一个值，该值指示 ValidTextBox 控件的 AutoComplete 行为。
        /// </summary>
        [DefaultValue(0), Themeable(false), Category("Behavior")]
        [Description("获取或设置一个值，该值指示 ValidTextBox 控件的 AutoComplete 。行为")]
        public virtual AutoCompleteType AutoCompleteType
        {
            get
            {
                object obj2 = this.ViewState["AutoCompleteType"];
                if (obj2 != null)
                {
                    return (AutoCompleteType)obj2;
                }

                return AutoCompleteType.None;
            }
            set
            {
                if ((value < AutoCompleteType.None) || (value > AutoCompleteType.Search))
                {
                    throw new ArgumentOutOfRangeException("value");
                }

                this.ViewState["AutoCompleteType"] = value;
            }
        }

        /// <summary>
        /// 获取或设置文本框中最多允许的字符数。
        /// </summary>
        [Category("Behavior"), DefaultValue(0), Themeable(false)]
        [Description("获取或设置文本框中最多允许的字符数。")]
        public virtual int MaxLength
        {
            get
            {
                object obj2 = this.ViewState["MaxLength"];
                if (obj2 != null)
                {
                    return (int)obj2;
                }

                return 0;
            }

            set
            {
                if (value < 0)
                {
                    throw new ArgumentOutOfRangeException("value");
                }

                this.ViewState["MaxLength"] = value;
            }
        }

        private bool SaveTextViewState
        {
            get
            {
                if (this.TextMode == TextBoxMode.Password)
                {
                    return false;
                }

                if (((base.Events[EventTextChanged] == null) && base.IsEnabled)
                    && ((this.Visible && !this.ReadOnly) && (base.GetType() == typeof(TextBox))))
                {
                    return false;
                }

                return true;
            }
        }

        /// <summary>
        /// 获取或设置文本框控件为一个必选字段。
        /// </summary>
        [Category("Behavior"), DefaultValue(false), Themeable(true)]
        [Description("获取或设置文本框控件为一个必选字段。")]
        public bool RequiredFieldValid
        {
            get
            {
                object o = ViewState["RequiredFieldValid"];
                return o != null ? (bool)o : false;
            }

            set
            {
                ViewState["RequiredFieldValid"] = value;
            }
        }

        /// <summary>
        /// 获取或设置 ValidTextBox 控件验证出错时的在客户端呈现的级联样式表 (CSS) 类。
        /// </summary>
        [Category("Behavior"), DefaultValue(""), Themeable(true)]
        [Description("获取或设置 ValidTextBox 控件验证出错时的在客户端呈现的级联样式表 (CSS) 类。")]
        public string ValueErrorCssClass
        {
            get
            {
                object o = ViewState["ValueErrorCssClass"];
                return o != null ? (string)o : string.Empty;
            }

            set
            {
                ViewState["ValueErrorCssClass"] = value;
            }
        }

        /// <summary>
        /// 获取或设置由 ValidTextBox 控件在客户端呈现的级联样式表 (CSS) 类。
        /// </summary>
        [Category("Appearance"), DefaultValue(""), Themeable(true)]
        [Description("获取或设置由 ValidTextBox 控件在客户端呈现的级联样式表 (CSS) 类。")]
        public new string CssClass
        {
            get
            {
                object o = ViewState["CssClass"];
                return o != null ? (string)o : string.Empty;
            }
            set
            {
                ViewState["CssClass"] = value;
            }
        }

        /// <summary>
        /// 获取或设置由 ValidTextBox 控件值改变时在客户端呈现的级联样式表 (CSS) 类。
        /// </summary>
        [Category("Appearance"), DefaultValue(""), CssClassProperty, Themeable(true)]
        [Description("获取或设置由 ValidTextBox 控件值改变时在客户端呈现的级联样式表 (CSS) 类。")]
        public string ValueChangeCssClass
        {
            get
            {
                object o = ViewState["ValueChangeCssClass"];
                return o != null ? (string)o : string.Empty;
            }

            set
            {
                ViewState["ValueChangeCssClass"] = value;
            }
        }

        /// <summary>
        /// 获取或设置 ValidTextBox 控件为一个必选字段时的级联样式表 (CSS) 类。
        /// </summary>
        [Category("Appearance"), DefaultValue(""), CssClassProperty, Themeable(true)]
        [Description("获取或设置由 ValidTextBox 控件为一个必选字段时的级联样式表 (CSS) 类。")]
        public string ValueRequiredCssClass
        {
            get
            {
                object o = ViewState["ValueRequiredCssClass"];
                return o != null ? (string)o : string.Empty;
            }

            set
            {
                ViewState["ValueRequiredCssClass"] = value;
            }
        }

        /// <summary>
        /// 获取或设置  ValidTextBox 控件值验证出错时的级联样式表 (CSS) 类。
        /// </summary>
        [Category("Appearance"), DefaultValue(""), CssClassProperty, Themeable(true)]
        [Description("获取或设置  ValidTextBox 控件值验证出错时的级联样式表 (CSS) 类。")]
        public string ErrorMessagePanelCssClass
        {
            get
            {
                object o = ViewState["ErrorMessagePanelCssClass"];
                return o != null ? (string)o : string.Empty;
            }

            set
            {
                ViewState["ErrorMessagePanelCssClass"] = value;
            }
        }


        /// <summary>
        /// 获取或设置  ValidTextBox 控件浏览状态时的级联样式表 (CSS) 类。
        /// </summary>
        [Category("Appearance"), DefaultValue(""), CssClassProperty, Themeable(true)]
        [Description("获取或设置  ValidTextBox 控件浏览状态时的级联样式表 (CSS) 类。")]
        public string ViewModeCssClass
        {
            get
            {
                object o = ViewState["ViewModeCssClass"];
                return o != null ? (string)o : string.Empty;
            }

            set
            {
                ViewState["ViewModeCssClass"] = value;
            }
        }

        /// <summary>
        /// 获取或设置 Web 服务器控件的前景色（通常是文本颜色）。 
        /// </summary>
        [DefaultValue(typeof(Color), "")]
        [Description("获取或设置 Web 服务器控件的前景色（通常是文本颜色）。")]
        public override System.Drawing.Color ForeColor
        {
            get
            {
                return base.ForeColor;
            }
            set
            {
                base.ForeColor = value;
            }
        }

        /// <summary>
        /// 获取或设置控件的初始验证值。
        /// </summary>
        [Category("Behavior"), DefaultValue("")]
        [Description("获取或设置控件的初始验证值。"), Themeable(false)]
        public string InitialValue
        {
            get
            {
                object obj2 = this.ViewState["InitialValue"];
                if (obj2 != null)
                {
                    return (string)obj2;
                }

                return string.Empty;
            }
            set
            {
                this.ViewState["InitialValue"] = value;
            }
        }

        /// <summary>
        /// 获取或设置用于验证的自定义客户端脚本函数的名称。
        /// </summary>
        /// <param name="?"></param>
        [DefaultValue(""), Category("Behavior"), Themeable(false)]
        [Description("获取或设置用于验证的自定义客户端脚本函数的名称。")]
        public string ClientValidationFunction
        {
            get
            {
                object obj2 = this.ViewState["ClientValidationFunction"];
                if (obj2 != null)
                {
                    return (string)obj2;
                }

                return string.Empty;
            }

            set
            {
                this.ViewState["ClientValidationFunction"] = value;
            }
        }

        /// <summary>
        /// 在服务器上执行验证时发生。
        /// </summary>
        [Description("在服务器上执行验证时发生。")]
        public event ServerValidateEventHandler ServerValidate
        {
            add
            {
                base.Events.AddHandler(EventServerValidate, value);
            }
            remove
            {
                base.Events.RemoveHandler(EventServerValidate, value);
            }
        }

        public ValidTextBox()
        {
            base.ForeColor = Color.Empty;
            base.CssClass = string.Empty;
            this.extensions = new ExtensionCollection<ValidTextBox>(this);
        }

        protected override void OnInit(EventArgs e)
        {
            this.ControlToValidate = this.ID;
            base.OnInit(e);
        }

        protected override void AddParsedSubObject(object obj)
        {
            if (!(obj is LiteralControl))
            {
                throw new HttpException("");
            }

            this.Text = ((LiteralControl)obj).Text;
        }

        protected virtual void OnTextChanged(EventArgs e)
        {
            EventHandler handler = (EventHandler)base.Events[EventTextChanged];
            if (handler != null)
            {
                handler(this, e);
            }
        }

        protected override bool EvaluateIsValid()
        {
            string controlValidationValue = base.GetControlValidationValue(base.ControlToValidate);

            try
            {
                //// 自定义验证
                ServerValidateEventHandler handler = (ServerValidateEventHandler)base.Events[ValidTextBox.EventServerValidate];
                ServerValidateEventArgs args = new ServerValidateEventArgs(controlValidationValue, true);
                if (handler != null)
                {
                    handler(this, args);
                    return args.IsValid;
                }
                else if (this.RequiredFieldValid)
                {
                    return ((controlValidationValue == null) || !controlValidationValue.Trim().Equals(this.InitialValue.Trim()));
                }
                else
                {
                    if (controlValidationValue == null || controlValidationValue.Length == 0)
                    {
                        return true;
                    }

                    Match match = Regex.Match(controlValidationValue, this.ValidationExpression);
                    return ((match.Success && (match.Index == 0)) && (match.Length == controlValidationValue.Length));
                }
            }
            catch
            {
                return true;
            }
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            if (this.DesignMode)
            {
                return;
            }

            bool isEditMode = this.GetEditMode();
            if (isEditMode)
            {
                #region 验证支持
                if (this.EnableClientScript)
                {
                    string clientID = this.ClientID;
                    this.Page.ClientScript.RegisterExpandoAttribute(clientID, "chgcls", this.ValueChangeCssClass);
                    this.Page.ClientScript.RegisterExpandoAttribute(clientID, "errcls", this.ValueErrorCssClass);
                    this.Page.ClientScript.RegisterExpandoAttribute(clientID, "rqdcls", this.ValueRequiredCssClass);
                    this.Page.ClientScript.RegisterExpandoAttribute(clientID, "errpnlcls", this.ErrorMessagePanelCssClass);
                    this.Page.ClientScript.RegisterExpandoAttribute(clientID, "cls", this.CssClass);
                    this.Page.ClientScript.RegisterExpandoAttribute(clientID, "rfv", this.RequiredFieldValid.ToString().ToLower());

                    this.Page.ClientScript.RegisterExpandoAttribute(clientID, "oldvalue", Microsoft.JScript.GlobalObject.escape(this.Text));
                    this.Page.ClientScript.RegisterExpandoAttribute(clientID, "customervalidatorupdatedisplay", "BeetleValidatorUpdateDisplay");

                    if (base.RenderUplevel && this.CausesValidation)
                    {
                        string regexStr = this.ValidationExpression ?? "";
                        regexStr = regexStr.Trim();

                        ////自定义客户端验证
                        if (!string.IsNullOrEmpty(this.ClientValidationFunction))
                        {
                            this.Page.ClientScript.RegisterExpandoAttribute(clientID, "evaluationfunction", this.ClientValidationFunction);
                        }
                        else if (this.RequiredFieldValid)
                        {
                            if (!string.IsNullOrEmpty(regexStr))
                            {
                                this.Page.ClientScript.RegisterExpandoAttribute(clientID, "evaluationfunction", "RequiredFieldAndRegularExpressionValidatorEvaluateIsValid");
                            }
                            else
                            {
                                this.Page.ClientScript.RegisterExpandoAttribute(clientID, "evaluationfunction", "RequiredFieldValidatorEvaluateIsValid");
                            }

                            this.Page.ClientScript.RegisterExpandoAttribute(clientID, "initialvalue", this.InitialValue);
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(regexStr))
                            {
                                this.Page.ClientScript.RegisterExpandoAttribute(clientID, "evaluationfunction", "RegularExpressionValidatorEvaluateIsValid");
                            }
                        }

                        if (this.ValidationExpression.Length > 0)
                        {
                            this.Page.ClientScript.RegisterExpandoAttribute(clientID, "validationexpression", this.ValidationExpression);
                        }
                    }
                }
                #endregion

                #region 文本框

                Page page = this.Page;
                if (page != null)
                {
                    page.VerifyRenderingInServerForm(this);
                }
                string uniqueID = this.UniqueID;
                if (uniqueID != null)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Name, uniqueID);
                }

                TextBoxMode textMode = this.TextMode;
                switch (textMode)
                {
                    case TextBoxMode.MultiLine:
                        {
                            int rows = this.Rows;
                            int columns = this.Columns;
                            bool flag = false;

                            if (rows == 0)
                            {
                                rows = 2;
                            }
                            if (columns == 0)
                            {
                                columns = 20;
                            }

                            if ((rows > 0) || flag)
                            {
                                writer.AddAttribute(HtmlTextWriterAttribute.Rows, rows.ToString(NumberFormatInfo.InvariantInfo));
                            }
                            if ((columns > 0) || flag)
                            {
                                writer.AddAttribute(HtmlTextWriterAttribute.Cols, columns.ToString(NumberFormatInfo.InvariantInfo));
                            }

                            if (!this.Wrap)
                            {
                                writer.AddAttribute(HtmlTextWriterAttribute.Wrap, "off");
                            }
                        }
                        break;
                    case TextBoxMode.SingleLine:
                        {
                            writer.AddAttribute(HtmlTextWriterAttribute.Type, "text");
                            if (((this.AutoCompleteType != AutoCompleteType.None) && (this.Context != null)) && (this.Context.Request.Browser["supportsVCard"] == "true"))
                            {
                                if (this.AutoCompleteType == AutoCompleteType.Disabled)
                                {
                                    writer.AddAttribute(HtmlTextWriterAttribute.AutoComplete, "off");
                                }
                                else if (this.AutoCompleteType == AutoCompleteType.Search)
                                {
                                    writer.AddAttribute(HtmlTextWriterAttribute.VCardName, "search");
                                }
                                else if (this.AutoCompleteType == AutoCompleteType.HomeCountryRegion)
                                {
                                    writer.AddAttribute(HtmlTextWriterAttribute.VCardName, "HomeCountry");
                                }
                                else if (this.AutoCompleteType == AutoCompleteType.BusinessCountryRegion)
                                {
                                    writer.AddAttribute(HtmlTextWriterAttribute.VCardName, "BusinessCountry");
                                }
                                else
                                {
                                    string str2 = Enum.Format(typeof(AutoCompleteType), this.AutoCompleteType, "G");
                                    if (str2.StartsWith("Business", StringComparison.Ordinal))
                                    {
                                        str2 = str2.Insert(8, ".");
                                    }
                                    else if (str2.StartsWith("Home", StringComparison.Ordinal))
                                    {
                                        str2 = str2.Insert(4, ".");
                                    }
                                    writer.AddAttribute(HtmlTextWriterAttribute.VCardName, "vCard." + str2);
                                }
                            }

                            string text = this.Text;
                            if (text.Length > 0)
                            {
                                writer.AddAttribute(HtmlTextWriterAttribute.Value, text);
                            }

                            break;
                        }
                    case TextBoxMode.Password:
                        writer.AddAttribute(HtmlTextWriterAttribute.Type, "password");
                        break;
                }

                int maxLength = this.MaxLength;
                if (textMode != TextBoxMode.MultiLine)
                {
                    if (maxLength > 0)
                    {
                        writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, maxLength.ToString(NumberFormatInfo.InvariantInfo));
                    }
                }

                maxLength = this.Columns;
                if (maxLength > 0)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Size, maxLength.ToString(NumberFormatInfo.InvariantInfo));
                }

                if (this.ReadOnly)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.ReadOnly, "readonly");
                }

                if ((this.AutoPostBack && (page != null)))
                {
                    string str4 = null;
                    if (base.HasAttributes)
                    {
                        str4 = base.Attributes["onchange"];
                        if (str4 != null)
                        {
                            str4 = Helper.EnsureEndWithSemiColon(str4);
                            base.Attributes.Remove("onchange");
                        }
                    }

                    PostBackOptions options = new PostBackOptions(this, string.Empty);
                    if (this.CausesValidation)
                    {
                        options.PerformValidation = true;
                        options.ValidationGroup = this.ValidationGroup;
                    }
                    if (page.Form != null)
                    {
                        options.AutoPostBack = true;
                    }

                    str4 = Helper.MergeScript(str4, page.ClientScript.GetPostBackEventReference(options, true));
                    writer.AddAttribute(HtmlTextWriterAttribute.Onchange, str4);
                    if (textMode != TextBoxMode.MultiLine)
                    {
                        string str5 = "if (WebForm_TextBoxKeyHandler(event) == false) return false;";
                        if (base.HasAttributes)
                        {
                            string str6 = base.Attributes["onkeypress"];
                            if (str6 != null)
                            {
                                str5 = str5 + str6;
                                base.Attributes.Remove("onkeypress");
                            }
                        }

                        writer.AddAttribute("onkeypress", str5);
                    }

                    writer.AddAttribute("language", "javascript", false);
                }
                else if (page != null)
                {
                    page.ClientScript.RegisterForEventValidation(this.UniqueID, string.Empty);
                }
                if (this.Enabled && !base.IsEnabled)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled");
                }

                #endregion
            }

            base.AddAttributesToRender(writer);
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);


            Page page = this.Page;
            if ((page != null) && base.IsEnabled)
            {
                if (!this.SaveTextViewState)
                {
                    Helper.RegisterEnabledControl(page, this);
                }

                if (this.AutoPostBack)
                {
                    Helper.RegisterWebFormsScript(page);
                    Helper.RegisterPostBackScript(page);
                    Helper.RegisterFocusScript(page);
                }

                string msgDiv = "<div id=\"__BeetleVALIDTEXTBOXMESSAGEDIV\" style=\"position: absolute; top: 0px; left: 0px; visibility: hidden;z-index:1000000;\"></div>";
                ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "ValidTextBox.DefaultErrorMessageDivString", msgDiv, false);
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            bool isEditMode = this.GetEditMode();

            if (isEditMode)
            {
                if (this.Page != null)
                {
                    this.Page.VerifyRenderingInServerForm(this);
                    this.RegisterValidatorDeclaration();
                }

                if (this.RequiredFieldValid)
                {
                    string cssclass = this.CssClass + " " + this.ValueRequiredCssClass;

                    cssclass = cssclass.Trim();
                    if (!string.IsNullOrEmpty(cssclass))
                    {
                        writer.AddAttribute("class", cssclass);
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(this.CssClass))
                    {
                        writer.AddAttribute("class", this.CssClass);
                    }
                }
            }
            else
            {
                writer.AddAttribute("class", this.ViewModeCssClass);
            }

            this.RenderBeginTag(writer);

            if (isEditMode)
            {
                if (this.TextMode == TextBoxMode.MultiLine)
                {
                    HttpUtility.HtmlEncode(this.Text, writer);
                }
            }
            else
            {
                writer.Write(this.Text);
            }

            this.RenderEndTag(writer);
        }

        protected override object SaveViewState()
        {
            if (!this.SaveTextViewState)
            {
                this.ViewState.SetItemDirty("Text", false);
            }

            return base.SaveViewState();
        }

        #region IPostBackDataHandler 成员

        public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
        {
            this.Page.ClientScript.ValidateEvent(postDataKey);
            string text = this.Text;
            string str2 = postCollection[postDataKey];

            if (!this.ReadOnly && !text.Equals(str2, StringComparison.Ordinal))
            {
                this.Text = str2;
                return true;
            }
            return false;
        }

        public void RaisePostDataChangedEvent()
        {
            if (this.AutoPostBack && !this.Page.IsPostBackEventControlRegistered)
            {
                this.Page.AutoPostBackControl = this;
                if (this.CausesValidation)
                {
                    this.Page.Validate(this.ValidationGroup);
                }
            }

            this.OnTextChanged(EventArgs.Empty);
        }

        #endregion

        #region IEditableTextControl 成员
        [Description("TextBox_OnTextChanged"), Category("Action")]
        public event EventHandler TextChanged
        {
            add
            {
                base.Events.AddHandler(EventTextChanged, value);
            }
            remove
            {
                base.Events.RemoveHandler(EventTextChanged, value);
            }
        }

        #endregion

        #region IExtensibleObject<ValidTextBox> 成员
        private ExtensionCollection<ValidTextBox> extensions = null;
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ExtensionCollection<ValidTextBox> Extensions
        {
            get
            {
                return this.extensions;
            }
        }

        #endregion

        #region IEditStatus 成员

        [DefaultValue(true)]
        public bool IsEditMode
        {
            get
            {
                object o = ViewState["IsEditMode"];
                return o != null ? (bool)o : true;
            }

            set
            {
                ViewState["IsEditMode"] = value;
            }
        }

        private bool? _InternalEditMode = null;
        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public bool? InternalEditMode
        {
            get
            {
                return this._InternalEditMode;
            }
        }

        public void SetInternalEditModeValue(bool? b)
        {
            this._InternalEditMode = b;
        }

        #endregion


        public bool CheckEditMode()
        {
            if (!this.IsEditMode)
            {
                return false;
            }

            return this.GetEditMode();
        }
    }
}
